from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Book
from .forms import BookForm, CheckoutForm
from .cart import Cart


def index(request):
    return render(request, 'ebooks/index.html')


def menu(request):
    return render(request, 'ebooks/menu.html')


def book_list(request):
    books = Book.objects.all()
    return render(request, 'ebooks/book_list.html', {'books': books})


def book_detail(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    return render(request, 'ebooks/book_detail.html', {'book': book})


@login_required
def book_create(request):
    if request.method == 'POST':
        form = BookForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('book_list')
    else:
        form = BookForm()
    return render(request, 'ebooks/book_create.html', {'form': form})


@login_required(login_url='login')
def book_update(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    if request.method == 'POST':
        form = BookForm(request.POST, request.FILES, instance=book)
        if form.is_valid():
            form.save()
            messages.success(request, 'Book updated successfully.')
            return redirect('book_detail', book_id=book_id)
    else:
        form = BookForm(instance=book)
    return render(request, 'ebooks/book_update.html', {'form': form})


@login_required(login_url='login')
def book_delete(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    if request.method == 'POST' and request.POST.get('confirm_delete') == 'yes':
        book.delete()
        messages.success(request, 'Book deleted successfully.')
        return redirect('book_list')
    return render(request, 'ebooks/book_delete.html', {'book': book})


def book_search(request):
    if request.method == 'POST':
        title_query = request.POST.get('title')
        author_query = request.POST.get('author')
        books = Book.objects.all()
        if title_query:
            books = books.filter(title__icontains=title_query)
        if author_query:
            books = books.filter(author__icontains=author_query)
        return render(request, 'ebooks/book_search_results.html', {'books': books})
    return render(request, 'ebooks/book_search.html')


@login_required(login_url='login')
def add_to_cart(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    cart = Cart(request)
    cart.add(book)
    return redirect('cart')

# hard to read, lots of nested if/else
# tip: design code so that it has at most three levels of indentation
@login_required(login_url='login')
def cart(request):
    cart = Cart(request)
    checkout_form = CheckoutForm()
    error_message = None
    final_price = request.session.get('final_price', 0)
    if request.method == 'POST':
        form = CheckoutForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            email_confirm = form.cleaned_data['email_confirm']
            if email != email_confirm:
                error_message = "Email addresses do not match."
            else:
                request.session['email'] = email
                final_price = cart.get_total_price()
                request.session['final_price'] = str(final_price)
                cart.clear()
                return redirect('checkout_success')
        else:
            error_message = form.errors.get('email_confirm', None)
    return render(request, 'ebooks/cart.html', {
        'cart': cart,
        'checkout_form': checkout_form,
        'error_message': error_message,
        'final_price': final_price
    })


def checkout_success(request):
    email = request.session.get('email')
    final_price = request.session.pop('final_price', 0)
    return render(request, 'ebooks/checkout_success.html',
                  {'email': email, 'final_price': final_price})


@login_required(login_url='login')
def remove_from_cart(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    cart = Cart(request)
    cart.remove(book)
    return redirect('cart')
